package com.ufo.store.management.adapter;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.entity.Member;
import com.ufo.store.management.utils.GlideUtils;
import com.ufo.store.management.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 *  作者：taoli on 2017/6/7 0007 14:29
 *  
 */
public class MemberRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Activity context = null;
    private List<Member> mMemberInfoList = null;
    private int[] colors = new int[]{Color.parseColor("#59c7bc"), Color.parseColor("#f16d3d"), Color.parseColor("#f24980"), Color.parseColor("#ffa857")};
    private OnClickListener mListener = null;
    private Typeface tf;
    private int mStyle;   // 1 : 列表   2： 网格
    private int lastPosition = -1;
    private int longPressedIndex = -1;
    private RequestOptions options;

    public MemberRecyclerViewAdapter(Activity context, int style) {
        this.context = context;
        this.mMemberInfoList = new ArrayList<Member>();
        this.mStyle = style;
        tf = Typeface.createFromAsset(context.getAssets(), "OpenSans-Light.ttf");
        options = new RequestOptions();
        options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
        options.transform(new GlideUtils.GlideCircleTransform(context));
        options.placeholder(R.drawable.anastasia_circle);
        options.error(R.drawable.anastasia_circle);
    }

    public void insertData(List<Member> data) {
        mMemberInfoList.addAll(data);
    }

    public void removeData(int pos) {
        mMemberInfoList.remove(pos);
    }

    public void setData(List<Member> data) {
        mMemberInfoList.clear();
        mMemberInfoList.addAll(data);
    }

    public List<Member> getData() {
        return mMemberInfoList;
    }

    public void setStyle(int s) {
        mStyle = s;
    }

    public void setLongPressedIndex(int index) {
        longPressedIndex = index;
    }

    public int getLongPressedIndex() {
        return longPressedIndex;
    }

    public Member getItem(int pos) {
        Member info = mMemberInfoList.get(pos);
        return info;
    }

    @Override
    public int getItemViewType(int position) {
        return mStyle;
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        holder.itemView.clearAnimation();
    }

    /**
     * @desc 自定义动画
     * @author taoli
     * @time 2017/6/9 0009
     */
    private void setAnimation(View viewToAnimate, int position) {
        if (position > lastPosition) {
            Animation translateAnimation = new TranslateAnimation(0, 0, 100, 0);
            translateAnimation.setDuration(700);
            translateAnimation.setInterpolator(new OvershootInterpolator());
            viewToAnimate.setAnimation(translateAnimation);
            lastPosition = position;
        } else if (position < lastPosition) {
            Animation translateAnimation = new TranslateAnimation(0, 0, -100, 0);
            translateAnimation.setDuration(700);
            translateAnimation.setInterpolator(new OvershootInterpolator());
            viewToAnimate.setAnimation(translateAnimation);
            lastPosition = position;
        }
    }

    class RecyclerViewHolder extends RecyclerView.ViewHolder {
        TextView memberCatalog;
        ImageView memberIconIv;
        ImageView member_catalog_iv;
        TextView memberNameTv;
        TextView memberCardIdTv;
        TextView memberMobileTv;
        TextView memberPointTv;
        RelativeLayout details_rl;
        ImageView menuIv;
        View maskV;
        TextView topTv;
        TextView bottomTv;

        public RecyclerViewHolder(View view) {
            super(view);
            memberCatalog = (TextView) view.findViewById(R.id.catalog);
            memberIconIv = (ImageView) view.findViewById(R.id.member_icon_iv);
            member_catalog_iv  = (ImageView) view.findViewById(R.id.member_catalog_iv);
            memberNameTv = (TextView) view.findViewById(R.id.member_name_tv);
            memberCardIdTv = (TextView) view.findViewById(R.id.member_cardid_tv);
            memberMobileTv = (TextView) view.findViewById(R.id.member_mobile_tv);
            memberPointTv = (TextView) view.findViewById(R.id.member_point_tv);
            details_rl = view.findViewById(R.id.details_rl);
            menuIv = (ImageView) view.findViewById(R.id.menu_iv);
            maskV = (View) view.findViewById(R.id.mask_v);
            topTv = (TextView) view.findViewById(R.id.top_iv);
            bottomTv = (TextView) view.findViewById(R.id.bottom_iv);
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder = null;
        if (viewType == 1) {
            holder = new RecyclerViewHolder(LayoutInflater.from(
                    this.context).inflate(R.layout.member_listitem, parent,
                    false));
        } else if (viewType == 2) {
            holder = new RecyclerViewHolder(LayoutInflater.from(
                    this.context).inflate(R.layout.member_recycleritem, parent,
                    false));
        }
        return holder;
    }

    @Override
    public int getItemCount() {
        return mMemberInfoList.size();
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        final Member memberInfo = getItem(position);
        if (memberInfo != null) {
            if (holder instanceof RecyclerViewHolder) {
                RecyclerViewHolder holder1 = (RecyclerViewHolder) holder;

                holder1.memberNameTv.setText(memberInfo.memberName);
              //  holder1.memberNameTv.setTypeface(tf);
                holder1.memberMobileTv.setText(memberInfo.memberMobile);
               // holder1.memberMobileTv.setTypeface(tf);
                holder1.memberCardIdTv.setText(memberInfo.memberCardid);
               // holder1.memberCardIdTv.setTypeface(tf);
                holder1.memberPointTv.setText(String.valueOf((int) memberInfo.memberPoint) + "积分");
               // holder1.memberPointTv.setTypeface(tf);

                if (mStyle == 1) {
//                    if (position % 4 == 0) {
//                        holder1.memberMobileTv.setBackgroundResource(R.drawable.shape_member_point_color00_bg);
//                        holder1.memberCardIdTv.setBackgroundResource(R.drawable.shape_member_point_color0_bg);
//                    } else if (position % 4 == 1) {
//                        holder1.memberMobileTv.setBackgroundResource(R.drawable.shape_member_point_color11_bg);
//                        holder1.memberCardIdTv.setBackgroundResource(R.drawable.shape_member_point_color1_bg);
//                    } else if (position % 4 == 2) {
//                        holder1.memberMobileTv.setBackgroundResource(R.drawable.shape_member_point_color22_bg);
//                        holder1.memberCardIdTv.setBackgroundResource(R.drawable.shape_member_point_color2_bg);
//                    } else if (position % 4 == 3) {
//                        holder1.memberMobileTv.setBackgroundResource(R.drawable.shape_member_point_color33_bg);
//                        holder1.memberCardIdTv.setBackgroundResource(R.drawable.shape_member_point_color3_bg);
//                    }
                    // 根据position获取分类的首字母的Char ascii值
                    int section = getSectionForPosition(position);

                    // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
                    if (position == getPositionForSection(section)) {
                        holder1.memberCatalog.setVisibility(View.VISIBLE);
                        holder1.memberCatalog.setText(memberInfo.getSortLetters());
                    } else {
                        holder1.memberCatalog.setVisibility(View.GONE);
                    }

                } else if (mStyle == 2) {
                    if (position % 4 == 0) {
                        holder1.memberMobileTv.setBackground(null);
                        holder1.memberCardIdTv.setBackground(null);
                    } else if (position % 4 == 1) {
                        holder1.memberMobileTv.setBackground(null);
                        holder1.memberCardIdTv.setBackground(null);
                    } else if (position % 4 == 2) {
                        holder1.memberMobileTv.setBackground(null);
                        holder1.memberCardIdTv.setBackground(null);
                    } else if (position % 4 == 3) {
                        holder1.memberMobileTv.setBackground(null);
                        holder1.memberCardIdTv.setBackground(null);
                    }
                    holder1.memberCatalog.setVisibility(View.GONE);
                }

                String str = memberInfo.getSortLetters();

                if (memberInfo.memberName.length() != 0) {
                    String s = memberInfo.memberName.substring(0, 0 + 1);
                    if (s.getBytes().length >= 2) {
                        Drawable memberBmp = initLetterResources(s, position);
                        holder1.member_catalog_iv.setImageDrawable(memberBmp);
                    } else {
                        Drawable memberBmp = initLetterResources(str, position);
                        holder1.member_catalog_iv.setImageDrawable(memberBmp);
                    }
                } else {
                    Drawable memberBmp = initLetterResources(str, position);
                    holder1.member_catalog_iv.setImageDrawable(memberBmp);
                }

                if (BarApplication.getInstance().mbStockDisplayPicture)
                    getPicDesc(position, memberInfo.memberId.trim(), holder1.memberIconIv);

                if (!holder1.menuIv.hasOnClickListeners()) {
                    holder1.menuIv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int pos = holder.getPosition();
                            mListener.onMenuClick(v, pos);
                        }
                    });
                }

                if (!holder1.maskV.hasOnClickListeners()) {
                    holder1.maskV.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int pos = holder.getPosition();
                            mListener.onMaskClick(v, pos);
                        }
                    });
                }

                if (!holder1.topTv.hasOnClickListeners()) {
                    holder1.topTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int pos = holder.getPosition();
                            mListener.onDeleteClick(pos);
                        }
                    });
                }

                if (!holder1.bottomTv.hasOnClickListeners()) {
                    holder1.bottomTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int pos = holder.getPosition();
                            mListener.onDetailClick(pos);
                        }
                    });
                }

                holder1.maskV.setVisibility(View.GONE);
                holder1.topTv.setVisibility(View.GONE);
                holder1.bottomTv.setVisibility(View.GONE);
                holder1.maskV.clearAnimation();
                holder1.topTv.clearAnimation();
                holder1.bottomTv.clearAnimation();
            }
        }

        // 进入动画
        setAnimation(holder.itemView, position);

        if (mListener != null) {
            /**
             * 这里加了判断，itemViewHolder.itemView.hasOnClickListeners()
             * 目的是减少对象的创建，如果已经为view设置了click监听事件,就不用重复设置了
             * 不然每次调用onBindViewHolder方法，都会创建两个监听事件对象，增加了内存的开销
             */
            if (!holder.itemView.hasOnClickListeners()) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getPosition();
                        mListener.onItemClick(v, pos);
                    }
                });
                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int pos = holder.getPosition();
                        mListener.onItemLongClick(v, pos);
                        return true;
                    }
                });
            }
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position, List payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            if (holder instanceof RecyclerViewHolder) {
                String payload = (String) payloads.get(0);
                final RecyclerViewHolder holder1 = (RecyclerViewHolder) holder;
                if (payload.equals("recovery")) {
                    ObjectAnimator mAnimatorCatalog = ObjectAnimator.ofFloat(holder1.member_catalog_iv, View.ROTATION_Y, 0, 90);
                    mAnimatorCatalog.setDuration(500);
                    mAnimatorCatalog.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                            holder1.member_catalog_iv.setAlpha(1f);
                            holder1.member_catalog_iv.setRotationY(0);
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            holder1.member_catalog_iv.setAlpha(0f);
                            holder1.member_catalog_iv.setRotationY(90);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    mAnimatorCatalog.start();

                    ObjectAnimator mAnimatorIcon = ObjectAnimator.ofFloat(holder1.memberIconIv, View.ROTATION_Y, 270, 360);
                    mAnimatorIcon.setDuration(500);
                    mAnimatorIcon.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                            holder1.memberIconIv.setAlpha(1f);
                            holder1.memberIconIv.setRotationY(270);
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            holder1.memberIconIv.setRotationY(0);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    mAnimatorIcon.setStartDelay(500);
                    mAnimatorIcon.start();
                } else if (payload.equals("exhibit")) {
                    ObjectAnimator mAnimatorIcon = ObjectAnimator.ofFloat(holder1.memberIconIv, View.ROTATION_Y, 0, 90);
                    mAnimatorIcon.setDuration(500);
                    mAnimatorIcon.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                            holder1.member_catalog_iv.setAlpha(0f);
                            holder1.member_catalog_iv.setRotationY(90);
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            holder1.memberIconIv.setAlpha(0f);
                            holder1.memberIconIv.setRotationY(270);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    mAnimatorIcon.start();

                    ObjectAnimator mAnimatorCatalog = ObjectAnimator.ofFloat(holder1.member_catalog_iv, View.ROTATION_Y, 270, 360);
                    mAnimatorCatalog.setDuration(500);
                    mAnimatorCatalog.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                            holder1.member_catalog_iv.setAlpha(1f);
                            holder1.member_catalog_iv.setRotationY(270);
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            holder1.member_catalog_iv.setRotationY(0);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    mAnimatorCatalog.setStartDelay(500);
                    mAnimatorCatalog.start();

                }else if (payload.equals("menu")) {
                    if (longPressedIndex != -1 && position == longPressedIndex) {
                        holder1.maskV.setVisibility(View.VISIBLE);
                        holder1.topTv.setVisibility(View.VISIBLE);
                        holder1.bottomTv.setVisibility(View.VISIBLE);
                        AnimationSet showAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_toshow_anim);
                        holder1.maskV.startAnimation(showAnimationSet);
                        if (mStyle == 1) {
                            AnimationSet leftAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_toleft_anim);
                            AnimationSet rightAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_toright_anim);
                            holder1.topTv.startAnimation(leftAnimationSet);
                            holder1.bottomTv.startAnimation(rightAnimationSet);
                        } else if (mStyle == 2) {
                            AnimationSet topAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_totop_anim);
                            AnimationSet bottomAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_tobottom_anim);
                            holder1.topTv.startAnimation(topAnimationSet);
                            holder1.bottomTv.startAnimation(bottomAnimationSet);
                        }
                    } else {
                        if (mStyle == 1) {
                            AnimationSet leftToCenterAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_lefttocenter_anim);
                            leftToCenterAnimationSet.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    holder1.topTv.setVisibility(View.GONE);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            holder1.topTv.startAnimation(leftToCenterAnimationSet);

                            AnimationSet rightToCenterAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_righttocenter_anim);
                            rightToCenterAnimationSet.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    holder1.bottomTv.setVisibility(View.GONE);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            holder1.bottomTv.startAnimation(rightToCenterAnimationSet);
                        } else if (mStyle == 2) {
                            AnimationSet topToCenterAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_toptocenter_anim);
                            topToCenterAnimationSet.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    holder1.topTv.setVisibility(View.GONE);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            holder1.topTv.startAnimation(topToCenterAnimationSet);

                            AnimationSet bottomToCenterAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_bottomtocenter_anim);
                            bottomToCenterAnimationSet.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    holder1.bottomTv.setVisibility(View.GONE);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            holder1.bottomTv.startAnimation(bottomToCenterAnimationSet);
                        }
                        holder1.maskV.setVisibility(View.GONE);
                        holder1.maskV.clearAnimation();
                    }
                }
            }
        }
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        return mMemberInfoList.get(position).getSortLetters().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < mMemberInfoList.size(); i++) {
            String sortStr = mMemberInfoList.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }
        return -1;
    }

    private void getPicDesc(final int position, final String memberId, final ImageView iv) {
        String downloadRUL = BarApplication.Qiniu_BaseDownloadHost + BarApplication.mStoreName + "_" + "memberId_" + memberId + ".jpg";
        RequestListener listener = new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable drawable, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                //if (dataSource == DataSource.MEMORY_CACHE) {
                //当图片位于内存缓存时，glide默认不会加载动画
                iv.startAnimation(AnimationUtils.loadAnimation(context, R.anim.fadein));
                //}
                return false;
            }
        };
        Glide.with(context).load(downloadRUL).apply(options).listener(listener).thumbnail(0.1f).into(iv);
    }

    private Drawable initLetterResources(String str, int position) {
        // 初始化画布
        int bitmapX = (int) Utils.dp2px(context.getResources(), 40);
        int bitmapY = (int) Utils.dp2px(context.getResources(), 40);
        Bitmap bitmapDrawable = Bitmap.createBitmap(bitmapX, bitmapY, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapDrawable);
        //画圆
        Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);// 防抖动
        mPaint.setFilterBitmap(true);// 用来对Bitmap进行滤波处理，这样，当你选择Drawable时，会有抗锯
        if (mStyle == 1) {
            //mPaint.setColor(colors[position % 4]);
            mPaint.setColor(Color.parseColor("#dcdcdc"));
        } else if (mStyle == 2) {
            mPaint.setColor(Color.parseColor("#ececec"));
        }
        canvas.drawCircle(bitmapX / 2, bitmapX / 2, bitmapX / 2, mPaint);
        //画字母
        mPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setTypeface(Typeface.DEFAULT);
        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(Utils.dp2px(context.getResources(), 20));
        Paint.FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
        Rect dst = new Rect(0, 0, bitmapX, bitmapX);
        int baseline = dst.top + (dst.bottom - dst.top - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
        canvas.drawText(str, dst.centerX(), baseline, mPaint);
        canvas.save();
        return new BitmapDrawable(context.getResources(), bitmapDrawable);
    }

    public void setOnClickListener(OnClickListener l) {
        mListener = l;
    }

    public interface OnClickListener {
        void onDetailClick(int position);

        void onDeleteClick(int position);

        void onItemClick(View v, int position);

        void onItemLongClick(View v, int position);

        void onMenuClick(View v, int position);

        void onMaskClick(View v, int position);
    }
}
